//TODO: Define the unmount function
#include "common_headers.h"

void unmountvfs31(char vfs_label[50])
{
	//DECLARATIONS
	int is_valid_file_vfs_label, is_unMounting_file_exist, is_mounted;
	FILE *fptr2=NULL;
	
	//INITIALIZATIONS
	is_valid_file_vfs_label = 0;
	is_unMounting_file_exist = 0;
	is_mounted = 0;
		
	//CHECK IS VFS MOUNTED
	is_mounted = validateMountStateBeforeUnmounting();
	if(is_mounted)
	{
		//CHECK IF VFS FILE EXISTS
		is_unMounting_file_exist = validateUnMountingFileExistance(vfs_label);		
		if(is_unMounting_file_exist==1)
		{
			//CHECK IF FILE NAME IS VALID ('/' IS NOT ALLOWED IN FILENAME)
			is_valid_file_vfs_label = validateUnMountingFileName(vfs_label);
			if(is_valid_file_vfs_label)
			{							
				fptr2=fopen(vfs_label,"rb+");			
				if(fptr2!=NULL)
				{
					//WRITING BACK TO FILE 
					fwrite(&mainHeader,sizeof(struct MainHeader),1,fptr2);
					fwrite(freelist,((mainHeader.maximumFileDescriptor)*sizeof(char)),1,fptr2);
		   			fwrite(fileDescriptors,(mainHeader.maximumFileDescriptor*sizeof(struct FileDescriptor)),1,fptr2);
					fclose(fptr2);
					free(freelist);
					free(fileDescriptors);
					//UPDATING THE "mountstate" TO 0
					mountstate=0;
					printf("unmountvfs_SUCCESS\n");					
				}
				else
				{
					//CANNOT_WRITE_TO_FILE (or) ACCESS DENIED
					printf("unmountvfs_FAILURE %s\n", ERR_VFS_UNMOUNT_02);		
				}			
			}
			else
			{
				//INVALID_CHARACTER_IN_NAME
				printf("unmountvfs_FAILURE %s\n", ERR_VFS_UNMOUNT_05);	 //To be added	
			}
		}
		else
		{
			//FILE CORRUPT (or) FILE DELETED ACCIDENTLY (or) DATA FILE NOT FOUND
			printf("unmountvfs_FAILURE %s\n", ERR_VFS_UNMOUNT_01);		
		}
	}
	else
	{
		//VFS_NOT_MOUNTED
		printf("unmountvfs_FAILURE %s\n", ERR_VFS_UNMOUNT_04);		
	}
}

